<?php

/**
 * http://projects:8081/cdapp-2kt-api/api/proxy_ntfm_loader.php
 *
 * Action:
 *   sudo ip add 172.22.215.0/24 via 10.202.91.254
 *   curl --location 'http://127.0.0.1/2kt/api/agent_ntfm_load.php'
 *
 * Crontab:
 *
 * Steps:
 *   1. ask real server for payload data and if required to load
 *   2. load tma data
 *   3. laod airport data
 *   4. laod diversion data
 *   5. upload data
 */

include_once '_portal.php';

$verbose = intval($_GET['verbose'] ?? ($_GET['v'] ?? 0));
define('VERBOSE', $verbose);

$force = intval($_GET['force'] ?? ($_GET['f'] ?? 0));
define('FORCE', $force);

echo PHP_EOL . 'agent_ntfm_load.php' . PHP_EOL . PHP_EOL . 'FORCE=' . $force . PHP_EOL . 'VERBOSE=' . $verbose . PHP_EOL . PHP_EOL;

// Host NTFM Module
const INIT_URI = 'http://' . HOST_IP . '/2kt/api/agent_ntfm_init.php';
const SAVE_URI = 'http://' . HOST_IP . '/2kt/api/agent_ntfm_save.php';

// NTFM Flow Forecast Module
const N_TMA_URI = 'http://' . NTFM_IP . ':9000/NTFM-FORE/forecast/sect/queryClassifyFlow';
const N_AP_URI = 'http://' . NTFM_IP . ':9000/NTFM-FORE/forecast/port/queryClassifyFlow';

// NTFM Normal Rate Module
const N_DNR_URI = 'http://' . NTFM_IP . ':8290/remote/map/NTFM-MONIT/monitor/efficacy/queryDailyNormalRate';
const N_HNR_URI = 'http://' . NTFM_IP . ':8290/remote/map/NTFM-MONIT/monitor/efficacy/queryHourNormalRate';

const DIV_DETAIL_URI = 'http://' . NTFM_IP . ':8330/remote/map/NTFM-PARA/formulate/getDiversionFlightsDetail';
const DIV_NEW_URI = 'http://' . NTFM_IP . ':8330/remote/map/NTFM-PARA/formulate/getDiversionFlightsNew';

$prep = request_init();
$data = [];

if (VERBOSE) {
  echo PHP_EOL . 'Prep:' . PHP_EOL;
  var_export($prep, false);
}

if ($prep['status'] > 0) {
  if ($prep['status_tma'] > 0) {
    $data['tma'] = load_ntfm_tma($prep['payload_tma']);
  }
  if ($prep['status_ap'] > 0) {
    $data['ap'] = load_ntfm_airport($prep['payload_ap']);
  }
  if ($prep['status_div'] > 0) {
    $data['div'] = load_ntfm_diversion($prep['payload_div']);
  }
  if ($prep) {
    $data['nrs'] = load_ntfm_normal_rates($prep['payload_nrs']);
  }
} else {
  echo PHP_EOL . '运行出错!' . PHP_EOL;
  logfile('NTFM_LOAD', '运行出错!');
}
// logfile('NTFM_LOAD', json_stringify($data));
$save_result = request_save($data);
echo PHP_EOL . '已结束' . PHP_EOL;
logfile('NTFM_LOAD', '已结束!');

if (VERBOSE) {
  echo PHP_EOL . 'Data:' . PHP_EOL;
  var_export($data, false);
  echo PHP_EOL . 'Result:' . PHP_EOL;
  var_export($save_result, false);
}

// 1. ask real server for payload data and if required to load
function request_init() {
  echo PHP_EOL . '正在获取Payload' . PHP_EOL;
  logfile('NTFM_LOAD', '正在获取Payload');
  $curl = curl_init();
  curl_setopt_array($curl, array(
    CURLOPT_URL => INIT_URI . '?force=' . FORCE,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'GET',
  ));
  $response = curl_exec($curl);
  // logfile('NTFM_LOAD', $response);
  curl_close($curl);
  if ($response == '') {
    echo PHP_EOL . '获取Payload失败' . PHP_EOL;
    logfile('NTFM_LOAD', '获取Payload失败');
    return [
      'status' => 0,
      'msg' => 'no response from server',
    ];
  } else {
    echo PHP_EOL . '已获取Payload' . PHP_EOL;
    logfile('NTFM_LOAD', '已获取Payload');
    $result = json_parse($response);
    return $result;
  }
}

// 2. load tma data
function load_ntfm_tma($payload) {
  echo PHP_EOL . '正在查询NTFM终端区数据' . PHP_EOL;
  logfile('NTFM_LOAD', '正在查询NTFM终端区数据');
  $curl = curl_init();
  curl_setopt_array($curl, array(
    CURLOPT_URL => N_TMA_URI,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 60,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => json_stringify($payload),
    CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
  ));
  $response = curl_exec($curl);
  // logfile('NTFM_LOAD', $response);
  curl_close($curl);
  if ($response == '') {
    echo PHP_EOL . '获取NTFM终端区数据失败' . PHP_EOL;
    logfile('NTFM_LOAD', '获取NTFM终端区数据失败');
    return ['status' => 0, 'response' => null];
  } else {
    echo PHP_EOL . '已获取NTFM终端区数据' . PHP_EOL;
    logfile('NTFM_LOAD', '已获取NTFM终端区数据');
    return ['status' => 1, 'response' => json_parse($response)];
  }
}

// 3. laod airport data
function load_ntfm_airport($payload) {
  $replies = [];
  foreach ($payload as $icao => $content) {
    echo PHP_EOL . '正在查询NTFM_' . $icao . '数据' . PHP_EOL;
    logfile('NTFM_LOAD', '正在查询NTFM_' . $icao . '数据');

    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => N_AP_URI,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 60,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'POST',
      CURLOPT_POSTFIELDS => json_stringify($content),
      CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
    ));

    $response = curl_exec($curl);
    // logfile('NTFM_LOAD', $response);
    curl_close($curl);
    $reply = null;

    if ($response == '') {
      echo PHP_EOL . '获取NTFM_' . $icao . '数据失败' . PHP_EOL;
      logfile('NTFM_LOAD', '获取NTFM' . $icao . '数据失败');
      $reply = ['status' => 0, 'response' => null];
    } else {
      echo PHP_EOL . '已获取NTFM_' . $icao . '数据' . PHP_EOL;
      logfile('NTFM_LOAD', '已获取NTFM' . $icao . '数据');
      $reply = ['status' => 1, 'response' => json_parse($response)];
    }

    $replies[$icao] = $reply;

  }

  return $replies;
}

// 4. load diversition data
function load_ntfm_diversion($payload) {
  echo PHP_EOL . '正在查询NTFM改航数据' . PHP_EOL;
  logfile('NTFM_LOAD', '正在查询NTFM改航数据');

  $url = DIV_DETAIL_URI . $payload;
  $curl = curl_init();

  curl_setopt_array($curl, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'GET',
  ));

  $response = curl_exec($curl);
  $response_obj = ['data' => []];
  curl_close($curl);
  $status = 0;
  $msg = '获取NTFM改航数据失败';

  if ($response && $response != '') {
    $response_obj = json_parse($response);
    $status = 1;
    $msg = '已获取NTFM改航数据';
  }

  echo PHP_EOL . $msg . PHP_EOL;
  logfile('NTFM_LOAD', $msg);

  if (!$status) {
    logfile('NTFM_LOAD:URL', $url);
    logfile('NTFM_LOAD:RES', $response);
  } else {
    // logfile('NTFM_LOAD:URL', $url);
    // logfile('NTFM_LOAD:RES', json_stringify($response_obj));
    // logfile('NTFM_LOAD:RES', $response);
  }

  return ['status' => $status, 'response' => $response_obj];
}

// 5. load normal rates
function load_ntfm_normal_rates($payload) {
  echo PHP_EOL . '正在查询NTFM正常率数据' . PHP_EOL;
  logfile('NTFM_LOAD', '正在查询NTFM正常率数据');
  $st = date('Y-m-d');
  $items = $payload['NORMAL_RATE_ITEMS'];
  $types = $payload['NORMAL_RATE_TYPES'];
  $results = [];
  foreach ($items as $item) {
    $results[$item] = [];
    $results[$item]['airport'] = $item;
    $dnr = load_ntfm_normal_rate_daily($item, $st);
    $results[$item]['dnr_flight'] = is_null($dnr) ? null : $dnr['normal_rate'];
    $results[$item]['dnr_dep'] = is_null($dnr) ? null : $dnr['normal_rate_dep'];
    $results[$item]['dnr_tkf'] = is_null($dnr) ? null : $dnr['normal_rate_tkf'];
    $results[$item]['dnr_arr'] = is_null($dnr) ? null : $dnr['normal_rate_arr'];
    $results[$item]['dnr_lnd'] = is_null($dnr) ? null : $dnr['normal_rate_lnd'];
    $results[$item]['dnr_start'] = is_null($dnr) ? null : $dnr['normal_rate_start'];
    $results[$item]['dnr_release'] = is_null($dnr) ? null : $dnr['normal_rate_release'];
    foreach ($types as $type) {
      $hnr = load_ntfm_normal_rate_hourly($item, $st, $type);
      $hnr_current = 0;
      if (!is_null($hnr)) {
        $res = $hnr['normalRate'];
        for ($i = count($res) - 1; $i >= 0; $i--) {
          if ($res[$i] != null) {
            $hnr_current = $res[$i];
          }
        }
      }
      // $results[$item]['hnr_' . $type] = is_null($hnr) ? null : $hnr['normalRate'];
      $results[$item]['hnr_' . $type] = $hnr_current;
    }
  }
  return $results;
}

function load_ntfm_normal_rate_daily($item, $st) {
  $curl = curl_init();
  curl_setopt_array($curl, array(
    CURLOPT_URL => N_DNR_URI,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => "item={$item}&st={$st}",
    CURLOPT_HTTPHEADER => array(
      'Content-Type: application/x-www-form-urlencoded',
    ),
  ));
  $response = curl_exec($curl);
  curl_close($curl);
  return parse_response($response);

}

function load_ntfm_normal_rate_hourly($item, $st, $type) {
  $curl = curl_init();
  curl_setopt_array($curl, array(
    CURLOPT_URL => N_HNR_URI,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => "item={$item}&st={$st}&type={$type}",
    CURLOPT_HTTPHEADER => array(
      'Content-Type: application/x-www-form-urlencoded',
    ),
  ));
  $response = curl_exec($curl);
  curl_close($curl);
  return parse_response($response);
}

function parse_response($response) {
  if ($response != null && $response != '' && $response) {
    $res_object = json_parse($response);
    if (gettype($res_object) == 'array') {
      return $res_object['data'];
    } else {
      return null;
    }
  } else {
    return null;
  }

}

// 6. upload data
function request_save($data) {
  echo PHP_EOL . '正在上传数据' . PHP_EOL;
  logfile('NTFM_LOAD', '正在上传数据');
  $curl = curl_init();
  curl_setopt_array($curl, array(
    CURLOPT_URL => SAVE_URI,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 60,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => json_stringify($data),
    CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
  ));
  $response = curl_exec($curl);
  // logfile('NTFM_LOAD', $response);
  curl_close($curl);
  if ($response == '') {
    echo PHP_EOL . '上传数据失败' . PHP_EOL;
    logfile('NTFM_LOAD', '上传数据失败');
    return ['status' => 0, 'response' => null];
  } else {
    echo PHP_EOL . '数据已上传' . PHP_EOL;
    logfile('NTFM_LOAD', '数据已上传');
    return ['status' => 1, 'response' => json_parse($response)];
  }
}